package three_autoAck;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import util.RabbitMqUtils;
import util.SleepUtil;

import java.nio.charset.StandardCharsets;

/**
 * @BelongsProject: RabbitMQ
 * @BelongsPackage: autoAck
 * @Author: HUI
 * @CreateTime: 2022-04-13 10:42
 * @Description:
 */
public class MyWorks {

    private static final String QUEUE_NAME = "ack_queue";

    public void getWork() throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {

            System.out.println("MyWorks睡眠時間短");
            SleepUtil.sleep(1);


            String receivedMessage = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("MyWorks" + "接收到消息:" + receivedMessage);



            /**
             * 1、消息标记
             * 2、是否批量处理未应答消息
             */
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

        };

        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println(consumerTag + "消费者取消消费接口回调逻辑");
        };

        System.err.println("MyWorks" + "消费者启动等待消费.................. ");

        //设置不公平分发
//        channel.basicQos(1);

        //设置预取值
        channel.basicQos(1);

        //采用手动应答
        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, cancelCallback);
    }


    public static void main(String[] args) throws Exception {

        new MyWorks().getWork();

    }

}
